﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SSharp.Core.DataTypes;
using SSharp.Core.Builtins.Functions.Util;
using SSharp.Core.Evaluator;
using System.Numerics;

namespace SSharp.Core.Builtins.Functions {
	public static class PrimitiveRandom {

		public static readonly PrimitiveProcedure Random = new PrimitiveProcedure("random",
			args => {
				Random rng = ThreadSafeRandom.getRng();
				if (args.Length == 0) {
					return rng.Next();
				} else if (args.Length == 1) {
					int a0 = validateInt("random", args[0]);
					return rng.Next(a0);
				} else if (args.Length == 2) {
					int a0 = validateInt("random", args[0]);
					int a1 = validateInt("random", args[1]);

					return rng.Next(a0, a1);
				} else {
					throw new ApplicationError("random expected zero to two arguments, given " + args.Length);
				}
			});

		private static int validateInt(string funcName, object arg) {
			decimal? asDec = arg as decimal?;
			if (asDec != null) {
				return (int)asDec.Value;
			}

			BigInteger? asBigInt = arg as BigInteger?;
			if (asBigInt != null) {
				return (int)asBigInt;
			}

			throw new InvalidOperationException(funcName + " expected integer argument, given " + arg);
		}
	}
}
